const obj = {
  name: "wade",
  age: 37,
  friend: {
    name: "james",
    age: 34,
    b: /\c/,
    c: new Date(),
  },
};

// const newObje = {};
// deepClone(obj, newObje);
// function deepClone(target, newObj) {
//   if (typeof target === "object") {
//     for (key in target) {
//       if (
//         target[key].constructor === RegExp ||
//         target[key].constructor === Date
//       ) {
//         newObj[key] = target[key];
//       } else {
//         newObj[key] = deepClone(target[key], {});
//       }
//     }
//   } else if (typeof target === "function") {
//     newObj = target;
//   } else {
//     newObj = target;
//   }

//   return newObj;
// }

// function deepClone(oldObj, newObj) {
//   for (var key in oldObj) {
//     var item = oldObj[key];
//     if (item instanceof Object) {
//       if (item instanceof Function) {
//         newObj[key] = item;
//       } else {
//         newObj[key] = {};
//         deepClone(item, newObj[key]);
//       }
//     } else if (item instanceof Array) {
//       newObj[key] = [];
//       deepClone(item, newObj[key]);
//     } else {
//       newObj[key] = item;
//     }
//   }
// }

function deepClone(target) {
  var result;
  if (typeof target === "object") {
    if (Array.isArray(target)) {
      result = [];
      for (var i in target) {
        result.push(deepClone(target[i]));
      }
    } else if (target === null) {
      result = null;
    } else if (target.constructor === RegExp || target.constructor === Date) {
      result = target;
    } else {
      result = {};
      for (var key in target) {
        result[key] = deepClone(target[key]);
      }
    }
  } else {
    result = target;
  }

  return result;
}

const newObje = deepClone(obj);
newObje.friend.name = "haha";
console.log(newObje);
console.log(obj);
